package com.ts.api.http.platform.biz;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gitee.apanlh.util.algorithm.encrypt.symmetric.AES;
import com.gitee.apanlh.util.base.*;
import com.gitee.apanlh.util.dataformat.JsonUtils;
import com.gitee.apanlh.util.id.IdUtils;
import com.gitee.apanlh.util.valid.ValidParam;
import com.gitee.apanlh.web.model.vo.RequestVO;
import com.ts.api.http.platform.entity.apply.ApiPlatApplyHuiYuanDai;
import com.ts.api.http.platform.entity.dataexchange.ApiPlatDataExchangeHuiYuanDai;
import com.ts.api.module.api.convert.core.annotation.ApiPlan;
import com.ts.api.module.api.convert.core.annotation.ApiPlanConvertType;
import com.ts.api.module.api.convert.core.entity.ApiApplyParameter;
import com.ts.api.module.api.convert.core.entity.ApiBizStatus;
import com.ts.api.module.api.convert.core.entity.ApiDataExchangeParameter;
import com.ts.api.module.api.convert.platform.entity.RespPlatformMultiPhoneMaskDataExchange;
import com.ts.api.module.api.convert.platform.entity.RespPlatformNoticeApply;
import com.ts.api.module.api.convert.platform.entity.RespPlatformPhoneMaskApply;
import com.ts.api.module.api.convert.platform.entity.RespPlatformPhoneMaskDataExchange;
import com.ts.api.module.api.convert.platform.handler.ApiPlatformPhoneMaskConvertHandler;
import com.ts.api.module.api.entity.ApiProtocol;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 安心分期-汇元贷 全流程8位 9A
 * 链接：https://docs.apipost.net/docs/detail/4c451416d095000?locale=zh-cn&target_id=2f6003b0ffe006
 *
 * @author gwc
 * @create 2025-08-19 下午3:13
 */
@ApiPlan(productId = "418", type = ApiPlanConvertType.PLAT_PHONE_MASK)
public class ApiPlatHuiYuanDaiPhontMaskConvert implements ApiPlatformPhoneMaskConvertHandler {

    public static final String KEY = "tcnf2oocfqei64oe";
    public static final String CHANNEL_CODE = "RFGXJ9";

    @Override
    public Object dataExchange(ApiDataExchangeParameter apiDataExchangeParameter) throws Exception {
        // 创建对应撞库实体类
        ApiPlatDataExchangeHuiYuanDai huiYuanDai = new ApiPlatDataExchangeHuiYuanDai();
        // 手机明文前8位
        huiYuanDai.setMobileYm(apiDataExchangeParameter.getPhoneMask());
        // 订单号
        huiYuanDai.setOutOrderNo(apiDataExchangeParameter.getReqId());
        // 姓名
        huiYuanDai.setRealName("默认姓名");
        // 年龄
        huiYuanDai.setAge(apiDataExchangeParameter.getAge());
        // 性别（1-男，0-女）
        String sex = ChooseEq.create()
                .when(apiDataExchangeParameter.getSex(), "1", "0")
                .when(apiDataExchangeParameter.getSex(), "0", "1")
                .end("1");
        huiYuanDai.setSex(sex);
        // 城市名称
        huiYuanDai.setCity(apiDataExchangeParameter.getCity());
        // 城市代码（6位）
        huiYuanDai.setCityCode(apiDataExchangeParameter.getAreaCode());
        // 省份名称
        huiYuanDai.setProvince(apiDataExchangeParameter.getProvinceName());
        // 省份代码（6位）
        huiYuanDai.setProvinceCode(apiDataExchangeParameter.getProvinceCode());
        // 用户IP地址
        if (ValidParam.isEmpty(apiDataExchangeParameter.getIp())){
            huiYuanDai.setUserIp("127.0.0.1");
        }else {
            huiYuanDai.setUserIp(apiDataExchangeParameter.getIp());
        }
        // 房子情况
        String house = ChooseEq.create()
                .when(apiDataExchangeParameter.getRealEstateInfo(), "1", "hu001")
                .when(apiDataExchangeParameter.getRealEstateInfo(), "2", "hu003")
                .when(apiDataExchangeParameter.getRealEstateInfo(), "3", "hu003")
                .when(apiDataExchangeParameter.getRealEstateInfo(), "4", "hu003")
                .when(apiDataExchangeParameter.getRealEstateInfo(), "5", "hu003")
                .when(apiDataExchangeParameter.getRealEstateInfo(), "6", "hu003")
                .end("hu001");
        huiYuanDai.setHouse(house);
        // 车子情况
        String car = ChooseEq.create()
                .when(apiDataExchangeParameter.getCarInfo(), "1", "car001")
                .when(apiDataExchangeParameter.getCarInfo(), "2", "car003")
                .when(apiDataExchangeParameter.getCarInfo(), "3", "car003")
                .when(apiDataExchangeParameter.getCarInfo(), "4", "car003")
                .end("car001");
        huiYuanDai.setCar(car);
        // 公积金情况
        String gongjijin = ChooseEq.create()
                .when(apiDataExchangeParameter.getProvidentFund(), "1", "gjj001")
                .when(apiDataExchangeParameter.getProvidentFund(), "2", "gjj004")
                .when(apiDataExchangeParameter.getProvidentFund(), "3", "gjj004")
                .when(apiDataExchangeParameter.getProvidentFund(), "4", "gjj004")
                .end("gjj001");
        huiYuanDai.setGjj(gongjijin);
        // 社保情况
        String shebao = ChooseEq.create()
                .when(apiDataExchangeParameter.getSocialSecurity(), "1", "sb001")
                .when(apiDataExchangeParameter.getSocialSecurity(), "2", "sb004")
                .when(apiDataExchangeParameter.getSocialSecurity(), "3", "sb004")
                .when(apiDataExchangeParameter.getSocialSecurity(), "4", "sb004")
                .end("sb001");
        huiYuanDai.setShebao(shebao);
        // 花呗情况
        String hbLimit = ChooseEq.create()
                .when(apiDataExchangeParameter.getHbLimit(), "1", "hb001")
                .when(apiDataExchangeParameter.getHbLimit(), "2", "hb003")
                .when(apiDataExchangeParameter.getHbLimit(), "3", "hb003")
                .when(apiDataExchangeParameter.getHbLimit(), "4", "hb003")
                .when(apiDataExchangeParameter.getHbLimit(), "5", "hb003")
                .end("hb001");
        huiYuanDai.setHuabei(hbLimit);
        // 白条情况
        String btLimit = ChooseEq.create()
                .when(apiDataExchangeParameter.getBtLimit(), "1", "bt001")
                .when(apiDataExchangeParameter.getBtLimit(), "2", "bt003")
                .when(apiDataExchangeParameter.getBtLimit(), "3", "bt003")
                .when(apiDataExchangeParameter.getBtLimit(), "4", "bt003")
                .when(apiDataExchangeParameter.getBtLimit(), "5", "bt003")
                .end("bt001");
        huiYuanDai.setBaitiao(btLimit);
        // 逾期情况
        String overdue = ChooseEq.create()
                .when(apiDataExchangeParameter.getOverdue(), "1", "yq001")
                .when(apiDataExchangeParameter.getOverdue(), "2", "yq004")
                .when(apiDataExchangeParameter.getOverdue(), "3", "yq004")
                .end("yq004");
        huiYuanDai.setYuqi(overdue);
        // 企业主情况
        String job = ChooseEq.create()
                .when(apiDataExchangeParameter.getCareer(), "1", "eo001")
                .when(apiDataExchangeParameter.getCareer(), "2", "eo001")
                .when(apiDataExchangeParameter.getCareer(), "3", "eo002")
                .when(apiDataExchangeParameter.getCareer(), "4", "eo001")
                .when(apiDataExchangeParameter.getCareer(), "5", "eo001")
                .end("eo001");
        huiYuanDai.setEnterpriseOwner(job);
        // 芝麻分
        String zhima = ChooseEq.create()
                .when(apiDataExchangeParameter.getSesameCredit(), "1", "zm003")
                .when(apiDataExchangeParameter.getSesameCredit(), "2", "zm003")
                .when(apiDataExchangeParameter.getSesameCredit(), "3", "zm004")
                .when(apiDataExchangeParameter.getSesameCredit(), "4", "zm005")
                .end("zm003");
        huiYuanDai.setZhimaScore(zhima);
        // 保单情况
        String baodanIs = ChooseEq.create()
                .when(apiDataExchangeParameter.getInsurancePolicy(), "1", "bd001")
                .when(apiDataExchangeParameter.getInsurancePolicy(), "2", "bd002")
                .when(apiDataExchangeParameter.getInsurancePolicy(), "3", "bd002")
                .when(apiDataExchangeParameter.getInsurancePolicy(), "4", "bd002")
                .end("bd001");
        huiYuanDai.setBaodan(baodanIs);
        // 加密
        AES aes = AES.createEcb(KEY.getBytes());
        String data = aes.encryptToBase64Str(JsonUtils.toJson(huiYuanDai));
        Map<String, Object> map = MapUtils.newHashMap(newMap -> {
            newMap.put("channelCode", CHANNEL_CODE);
            newMap.put("requestNo", IdUtils.getSimpleUuid());
            newMap.put("tranData", data);
        });
        return JsonUtils.toJson(map);
    }

    @Override
    public RespPlatformMultiPhoneMaskDataExchange respDataExchange(String respJson) throws Exception {
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespPlatformMultiPhoneMaskDataExchange.ofFail();
        }
        if (!Eq.object(jsonObject.getString("status"), "000")) {
            return RespPlatformMultiPhoneMaskDataExchange.ofFail();
        }
        // 获取响应数据
        JSONObject resData = jsonObject.getJSONObject("data");
        if (ValidParam.isEmpty(resData)) {
            return RespPlatformMultiPhoneMaskDataExchange.ofFail();
        }

        RespPlatformMultiPhoneMaskDataExchange respPlatformMultiPhoneMaskDataExchange = RespPlatformMultiPhoneMaskDataExchange.ofSuc();
        List<RespPlatformPhoneMaskDataExchange> listRespPlatformPhoneMaskDataExchange = CollUtils.newArrayList();

        // 获取携带参数
        String orderId = resData.getString("orderNo");
        String productName = resData.getString("productName");
        String companyName = resData.getString("companyName");
        String logo = resData.getString("logo");
        // 用户协议
        List<ApiProtocol> protocolList = new ArrayList<>();
        // 获取协议
        JSONArray listProtocolResult = resData.getJSONArray("protocolList");
        IteratorUtils.array(listProtocolResult, (item, index) -> {
            JSONObject protocolObject = listProtocolResult.getJSONObject(index);
            ApiProtocol protocol = new ApiProtocol();
            protocol.setProtocolName(protocolObject.getString("protocolName"));
            protocol.setProtocolUrl(protocolObject.getString("protocolUrl"));
            protocolList.add(protocol);
        });
        // 获取手机号掩码
        List<String> listPhoneMd5 = new ArrayList<>();
        JSONArray jsonArray = resData.getJSONArray("md5List");
        IteratorUtils.array(jsonArray, (item, index) -> {
            String phoneMd5  = jsonArray.getString(index);
            listPhoneMd5.add(phoneMd5);
        });

        RespPlatformPhoneMaskDataExchange result = RespPlatformPhoneMaskDataExchange.of();

        result.setApplyId(orderId);
        result.setProductName(productName);
        result.setProtocolList(protocolList);
        result.setListPhoneMd5(listPhoneMd5);
        result.setDisplayName(companyName);
        result.setLogoPath(logo);
        listRespPlatformPhoneMaskDataExchange.add(result);

        respPlatformMultiPhoneMaskDataExchange.setListPhoneMask(listRespPlatformPhoneMaskDataExchange);
        return respPlatformMultiPhoneMaskDataExchange;
    }

    @Override
    public Object apply(ApiApplyParameter apiApplyParameter) throws Exception {
        // 创建进件实体类
        ApiPlatApplyHuiYuanDai huiYuanDai = new ApiPlatApplyHuiYuanDai();
        // 手机号码
        huiYuanDai.setMobile(apiApplyParameter.getPhone());
        // 手机md5转小写
        huiYuanDai.setMobileMd5(apiApplyParameter.getPhoneMd5().toLowerCase());
        // 姓名
        huiYuanDai.setRealName(apiApplyParameter.getUserName());
        // 年龄
        huiYuanDai.setAge(apiApplyParameter.getAge());
        // 性别（1 男 0 女）
        String sex = ChooseEq.create()
                .when(apiApplyParameter.getSex(), "1", "0")
                .when(apiApplyParameter.getSex(), "0", "1")
                .end("1");
        huiYuanDai.setSex(sex);
        // 城市名称
        huiYuanDai.setCity(apiApplyParameter.getCity());
        // 城市代码（6位）
        huiYuanDai.setCityCode(apiApplyParameter.getAreaCode());
        // 省份名称
        huiYuanDai.setProvince(apiApplyParameter.getProvinceName());
        // 省份代码（6位）
        huiYuanDai.setProvinceCode(apiApplyParameter.getProvinceCode());
        // 用户IP地址
        if (ValidParam.isEmpty(apiApplyParameter.getIp())){
            huiYuanDai.setUserIp("127.0.0.1");
        }else {
            huiYuanDai.setUserIp(apiApplyParameter.getIp());
        }
        String house = ChooseEq.create()
                .when(apiApplyParameter.getRealEstateInfo(), "1", "hu001")
                .when(apiApplyParameter.getRealEstateInfo(), "2", "hu003")
                .when(apiApplyParameter.getRealEstateInfo(), "3", "hu003")
                .when(apiApplyParameter.getRealEstateInfo(), "4", "hu003")
                .when(apiApplyParameter.getRealEstateInfo(), "5", "hu003")
                .when(apiApplyParameter.getRealEstateInfo(), "6", "hu003")
                .end("hu001");
        huiYuanDai.setHouse(house);
        // 车子情况
        String car = ChooseEq.create()
                .when(apiApplyParameter.getCarInfo(), "1", "car001")
                .when(apiApplyParameter.getCarInfo(), "2", "car003")
                .when(apiApplyParameter.getCarInfo(), "3", "car003")
                .when(apiApplyParameter.getCarInfo(), "4", "car003")
                .end("car001");
        huiYuanDai.setCar(car);
        // 公积金
        String gongjijin = ChooseEq.create()
                .when(apiApplyParameter.getProvidentFund(), "1", "gjj001")
                .when(apiApplyParameter.getProvidentFund(), "2", "gjj004")
                .when(apiApplyParameter.getProvidentFund(), "3", "gjj004")
                .when(apiApplyParameter.getProvidentFund(), "4", "gjj004")
                .end("gjj001");
        huiYuanDai.setGjj(gongjijin);
        // 社保
        String shebao = ChooseEq.create()
                .when(apiApplyParameter.getSocialSecurity(), "1", "sb001")
                .when(apiApplyParameter.getSocialSecurity(), "2", "sb004")
                .when(apiApplyParameter.getSocialSecurity(), "3", "sb004")
                .when(apiApplyParameter.getSocialSecurity(), "4", "sb004")
                .end("sb001");
        huiYuanDai.setShebao(shebao);
        // 商业保险
        String baodanIs = ChooseEq.create()
                .when(apiApplyParameter.getInsurancePolicy(), "1", "bd001")
                .when(apiApplyParameter.getInsurancePolicy(), "2", "bd002")
                .when(apiApplyParameter.getInsurancePolicy(), "3", "bd002")
                .when(apiApplyParameter.getInsurancePolicy(), "4", "bd002")
                .end("bd001");
        huiYuanDai.setBaodan(baodanIs);
        // 芝麻分
        String zhima = ChooseEq.create()
                .when(apiApplyParameter.getSesameCredit(), "1", "zm003")
                .when(apiApplyParameter.getSesameCredit(), "2", "zm003")
                .when(apiApplyParameter.getSesameCredit(), "3", "zm004")
                .when(apiApplyParameter.getSesameCredit(), "4", "zm005")
                .end("zm003");
        huiYuanDai.setZhimaScore(zhima);
        // 花呗情况
        String hbLimit = ChooseEq.create()
                .when(apiApplyParameter.getHbLimit(), "1", "hb001")
                .when(apiApplyParameter.getHbLimit(), "2", "hb003")
                .when(apiApplyParameter.getHbLimit(), "3", "hb003")
                .when(apiApplyParameter.getHbLimit(), "4", "hb003")
                .when(apiApplyParameter.getHbLimit(), "5", "hb003")
                .end("hb001");
        huiYuanDai.setHuabei(hbLimit);
        // 白条情况
        String btLimit = ChooseEq.create()
                .when(apiApplyParameter.getBtLimit(), "1", "bt001")
                .when(apiApplyParameter.getBtLimit(), "2", "bt003")
                .when(apiApplyParameter.getBtLimit(), "3", "bt003")
                .when(apiApplyParameter.getBtLimit(), "4", "bt003")
                .when(apiApplyParameter.getBtLimit(), "5", "bt003")
                .end("bt001");
        huiYuanDai.setBaitiao(btLimit);
        // 逾期情况
        String overdue = ChooseEq.create()
                .when(apiApplyParameter.getOverdue(), "1", "yq001")
                .when(apiApplyParameter.getOverdue(), "2", "yq004")
                .when(apiApplyParameter.getOverdue(), "3", "yq004")
                .end("yq004");
        huiYuanDai.setYuqi(overdue);
        // 企业主情况
        String job = ChooseEq.create()
                .when(apiApplyParameter.getCareer(), "1", "eo001")
                .when(apiApplyParameter.getCareer(), "2", "eo001")
                .when(apiApplyParameter.getCareer(), "3", "eo002")
                .when(apiApplyParameter.getCareer(), "4", "eo001")
                .when(apiApplyParameter.getCareer(), "5", "eo001")
                .end("eo001");
        huiYuanDai.setEnterpriseOwner(job);
        // 撞库接口返回的订单号
        huiYuanDai.setOrderNo(apiApplyParameter.getApplyId());
        // 加密
        AES aes = AES.createEcb(KEY.getBytes());
        String data = aes.encryptToBase64Str(JsonUtils.toJson(huiYuanDai));
        Map<String, Object> map = MapUtils.newHashMap(newMap -> {
            newMap.put("channelCode", CHANNEL_CODE);
            newMap.put("requestNo", IdUtils.getSimpleUuid());
            newMap.put("tranData", data);
        });
        return JsonUtils.toJson(map);
    }

    @Override
    public RespPlatformPhoneMaskApply respApply(String respJson) throws Exception {
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespPlatformPhoneMaskApply.ofFail();
        }
        if (!Eq.object(jsonObject.getString("status"), "000")) {
            return RespPlatformPhoneMaskApply.ofFail();
        }
        return RespPlatformPhoneMaskApply.ofSuc();
    }

    @Override
    public RespPlatformNoticeApply parseApplyNotice(RequestVO requestVO) {
        return null;
    }

    @Override
    public Map<String, Object> respApplyNotice(ApiBizStatus apiBizStatus) {
        return Map.of();
    }
}
